package unimelb.filesync.common.protocol;

import java.util.concurrent.BlockingQueue;

import unimelb.filesync.common.message.FileSyncRequest;
import unimelb.filesync.common.misc.ProtocolContext;
import filesync.EndUpdateInstruction;
import filesync.Instruction;
import filesync.StartUpdateInstruction;
import filesync.SynchronisedFile;

public class PopulateInstructionQueueTask implements Runnable {

    private final SynchronisedFile syncFile;

    private final BlockingQueue<FileSyncRequest> writeMsgQueue;

    private long sequenceId = 0;

    private long instructionId = 0;

    public PopulateInstructionQueueTask(SynchronisedFile syncFile, ProtocolContext context) {
        super();
        this.syncFile = syncFile;
        this.writeMsgQueue = context.getObject(ProtocolContext.WRITE_MSG_QUEUE);
    }

    @Override
    public void run() {
        while (true) {
            FileSyncRequest syncMsg = null;

            final Instruction currentInstruction = syncFile.NextInstruction();
            if (currentInstruction instanceof StartUpdateInstruction) {
                syncMsg = new FileSyncRequest(currentInstruction, sequenceId, instructionId);
                instructionId++;
            } else if (currentInstruction instanceof EndUpdateInstruction) {
                syncMsg = new FileSyncRequest(currentInstruction, sequenceId, instructionId);
                sequenceId++;
                instructionId = 0;
            } else {
                syncMsg = new FileSyncRequest(currentInstruction, sequenceId, instructionId);
                instructionId++;
            }

            try {
                writeMsgQueue.put(syncMsg);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
